<?php
namespace control;
/*
*用章记录类
*/


class stampRecordClass extends adIndexClass
{
    private const title = '用章记录';
    private const page = 'stampRecord';
    private const table = 'seal_record';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            case 'allSearch':
                $tr = [
                    'orderNo'      => [
                        'name'  => "单据编号",
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'stid'      => [
                        'name'  => "申请人",
                        'width' => 100,
                    ],
                    'deptName' => [
                        'name'  => "申请人部门",
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'sealName'  => [
                        'name'  => "印章名称",
                        'width' => 120,
                    ],
                    'text'         => [
                        'name'  => '用途说明',
                        'width' => 100,
                    ],
                    'isOut'          => [
                        'name'  => '是否外带',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'member'          => [
                        'name'  => '同行人',
                        'width' => 100,
                    ],
                    'outDay'          => [
                        'name'  => '外带天数',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'fileNum'          => [
                        'name'  => '份数',
                        'width' => 160,
                    ],
                    'time'          => [
                        'name'  => '申请日期',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'sealDate'          => [
                        'name'  => '用章日期',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'sealNum'          => [
                        'name'  => '用章份数',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'borrowDate'          => [
                        'name'  => '借出日期',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'exReturnDate'          => [
                        'name'  => '应还日期',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'returnDate'          => [
                        'name'  => '实际归还日期',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'workFlow'          => [
                        'name'  => '状态',
                        'width' => 150,
                        'sort' => 1,
                    ]
                ];
                break;
            case 'borrowedSearch':
                $tr = [
                    'orderNo'      => [
                        'name'  => "单据编号",
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'stid'      => [
                        'name'  => "申请人",
                        'width' => 100,
                    ],
                    'deptName' => [
                        'name'  => "申请人部门",
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'sealName'  => [
                        'name'  => "印章名称",
                        'width' => 120,
                    ],
                    'text'         => [
                        'name'  => '用途说明',
                        'width' => 100,
                    ],
                    'isOut'          => [
                        'name'  => '是否外带',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'member'          => [
                        'name'  => '同行人',
                        'width' => 100,
                    ],
                    'outDay'          => [
                        'name'  => '外带天数',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'fileNum'          => [
                        'name'  => '份数',
                        'width' => 160,
                    ],
                    'time'          => [
                        'name'  => '申请日期',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'borrowDate'          => [
                        'name'  => '借出日期',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'returnSeal'          => [
                        'name'  => '已还印章',
                        'width' => 150,
                    ],
                    'workFlow'          => [
                        'name'  => '状态',
                        'width' => 150,
                        'sort' => 1,
                    ]
                ];
                break;
            default:
                $tr = [
                    'orderNo'      => [
                        'name'  => "单据编号",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'stid'      => [
                        'name'  => "申请人",
                        'width' => 120,
                    ],
                    'deptName' => [
                        'name'  => "申请人部门",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'sealName'  => [
                        'name'  => "印章名称",
                        'width' => 150,
                    ],
                    'text'         => [
                        'name'  => '用途说明',
                        'width' => 200,
                    ],
                    'isOut'          => [
                        'name'  => '是否外带',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'member'          => [
                        'name'  => '同行人',
                        'width' => 150,
                    ],
                    'outDay'          => [
                        'name'  => '外带天数',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'fileNum'          => [
                        'name'  => '份数',
                        'width' => 100,
                    ],
                    'time'          => [
                        'name'  => '申请日期',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'workFlow'          => [
                        'name'  => '状态',
                        'width' => 150,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /**
     * 查询表单
     *
     * @param string $workFlow
     * @return string
     */
    public function homeForm(string $workFlow): string
    {
        $array = [
            [
                [
                    "是否外带" => select(["name" => "isOut", 'option' => ['是', '否']]),
                    "单据编号"     => text(array("name" => "orderNo")),
                    '申请人'   => selectMultiple(array("name" => "stid", "class" => "width200", 'sqlId' => 'stid', 'sqlField' => 'name', 'table' => 'staff')),
                ],
                [

                    "申请人部门"     => text(array("name" => "deptName")),
                    '印章名称'   => selectMultiple(array("name" => "sealId", "class" => "width200", 'sqlId' => 'id', 'sqlField' => 'name', 'table' => 'seal')),
                    "用途说明"     => text(array("name" => "text")),
                ]
            ]
        ];
        if ($workFlow == '待用章') {
            $array[0][] = [
                "申请日期" => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~']))
            ];
        }
        return $this->tableShow($array,1);
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('待用章');
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*客户列表-查询条件*/
    public function home(): string
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('{$this->get('cla')}','seal',{})\" class='spanButton'>盖章</span>\n";
            $button .= "<span onclick=\"layer('{$this->get('cla')}','out',{})\" class='spanButton'>外借</span>\n";
        }
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch(): bool|string
    {
        //like查询数组
        $like = array(
            "deptName" => $this->post('deptName'),
            "text" => $this->post('text'),//标题
            "orderNo" => $this->post('orderNo'),
            "name" => $this->post('sealId'),
        );
        //全等查询数组
        $equal = array(
            'workFlow' => '待用章',
            'state' => '已通过',
            "stid" => $this->post('stid'),
            'isOut' => $this->post('isOut')
        );

        $and = "";
        if ($this->post('time')) {
            $and .= self::timeComparison($this->post('time'));
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $obj = new performanceScoreClass();
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "sealName":
                        $row[] = sealRecordClass::showSealName($array['name']);
                        break;
                    case "member":
                        $row[] = $obj->findMember($array['member'], 2);
                        break;
                    case "time":
                        $row[] = date('Y-m-d', strtotime($array['time']));
                        break;
                    case "stid":
                        $row[] = self::findStaff($array['stid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(fileNum),0) as fileNum",
        ]);
        $total    = [
            'fileNum'        => $totalQuery['fileNum'],
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function borrowedOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('待归还');
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /**
     * 待归还
     *
     */
    public function borrowed(): bool|string
    {
        $html = $this->borrowedOptions(false);
        $button = "";
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /**
     * 待归还
     * @return bool|string
     */
    public function borrowedSearch(): bool|string
    {
        //like查询数组
        $like = array(
            "deptName" => $this->post('deptName'),
            "text" => $this->post('text'),//标题
            "orderNo" => $this->post('orderNo'),
            "name" => $this->post('sealId'),
        );
        //全等查询数组
        $equal = array(
            'state' => '已通过',
            "stid" => $this->post('stid'),
            'isOut' => $this->post('isOut')
        );
        $and = " and workFlow in ('待归还','部分归还')";
        if ($this->post('time')) {
            $and .= self::timeComparison($this->post('time'), field: 'borrowDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("abolishedForm", "abolishedId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "abolishedId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $array['id'] . "')"),
                'rework' => array('title' => '归还', 'click' => "layer('" . self::page . "','sealBack',{id:'" . $array['id'] . "'})")
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "sealName":
                        $row[] = sealRecordClass::showSealName($array['name']);
                        break;
                    case "member":
                        $row[] = self::findStaff(explode(',', $array['member']));
                        break;
                    case "time":
                        $row[] = date('Y-m-d', strtotime($array['time']));
                        break;
                    case "returnSeal":
                        $row[] = sealRecordClass::showSealName($array['returnSeal']);
                        break;
                    case "stid":
                        $row[] = self::findStaff($array['stid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(fileNum),0) as fileNum",
        ]);
        $total    = [
            'fileNum'        => $totalQuery['fileNum'],
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 150),
            "orderBySign" => $orderBy,
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='abolishedForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function allOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('全部');
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /**
     * 待归还
     *
     */
    public function all(): bool|string
    {
        $html = $this->allOptions(false);
        //控件
        $button = '';
        if ($this->power('stampRecordAll', "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /**
     * 全部
     * @return bool|string
     */
    public function allSearch(): bool|string
    {
        //like查询数组
        $like = array(
            "deptName" => $this->post('deptName'),
            "text" => $this->post('text'),//标题
            "orderNo" => $this->post('orderNo'),
            "name" => $this->post('sealId'),
        );
        //全等查询数组
        $equal = array(
            'state' => '已通过',
            "stid" => $this->post('stid'),
            'isOut' => $this->post('isOut')
        );
        $and = "";
        if ($this->post('time')) {
            $and .= self::timeComparison($this->post('time'), field: 'borrowDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        $_SESSION['stampRecordAll']['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("allForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "sealName":
                        $row[] = sealRecordClass::showSealName($array['name']);
                        break;
                    case "member":
                        $row[] = self::findStaff(explode(',', $array['member']));
                        break;
                    case "time":
                        $row[] = date('Y-m-d', strtotime($array['time']));
                        break;
                    case "stid":
                        $row[] = self::findStaff($array['stid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(fileNum),0) as fileNum",
        ]);
        $total    = [
            'fileNum'        => $totalQuery['fileNum'],
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 150),
            "orderBySign" => $orderBy,
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='allForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power('stampRecordAll', 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::table,
                    "where" => "id in ('".implode("','", $checkedId)."') order by time desc",
                ))['array'];
            }else{
                $sql   = $_SESSION['stampRecordAll']['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '单据编号'=>$array['orderNo'],
                            '申请人'=>self::findStaff($array['stid']),
                            '申请人部门'=>$array['deptName'],
                            '印章名称'=>sealRecordClass::showSealName($array['name']),
                            '用途说明'=>$array['text'],
                            '是否外带'=>$array['isOut'],
                            '同行人'=> self::findStaff(explode(',', $array['member'])),
                            '外带天数'=>$array['outDay'],
                            '份数'=>$array['fileNum'],
                            '申请日期'=> date('Y-m-d', strtotime($array['time'])),
                            '用章日期'=>$array['sealDate'],
                            '用章份数'=>$array['sealNum'],
                            '借出日期'=>$array['borrowDate'],
                            '应还日期'=>$array['exReturnDate'],
                            '实际归还日期'=>$array['returnDate'],
                            '状态'=>$array['workFlow'],
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }

            $text = $this->control['name'] . "导出了用章记录";
            $this->logText(["type" => 'stampRecordAll', "text" => $text]);
            $this->excelOut($title, $data, "用章记录.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /**
     * 归还
     * @return bool|string
     */
    public function sealBack(): bool|string
    {
        $info = query(self::table, "id = '" . $this->post('id') . "'");
        $sealOption = [];
        $all = find(array('table' => 'seal', 'where' => "isOccupy =1 and id in ('" . implode("','", explode(',', $info['name'])) . "') order by recordDate asc,time asc"));
        foreach ($all['array'] as $array) {
            $sealOption[$array['id']] = $array['name'];
        }
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must . "归还日期：" => text(array('name' => 'signTime', 'laydate' => [], 'value' => $this->date)),
            ),
            array(
                must . "印章名称：" => checkbox(["name" => "name", 'value' => $sealOption, 'checked' => []])
            ),
            array(
                "备注：" => textarea(array('name' => 'text', 'class' => 'textarea')),
            )
        )));
        //返回
        return $this->layer(array("title" => "归还", "height" => 380, "width" => 800, "html" => $html));
    }


    /**
     * 归还编辑
     */
    public function sealBackEdit(): bool|string
    {
        $returnSeal = $this->post('name') ?: [];
        $field = [
            'returnStid' => self::$stid,
            'returnDate' => $this->post('signTime'),
        ];
        $info = query(self::table, "id = '" . $this->post('id') . "'");
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有" . self::title . "的编辑权限";
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此用章记录';
        } elseif ($info['workFlow'] == '已归还') {
            $json['warn'] = '此用章申请已归还,无需再次提交';
        } elseif (static::is_null_array($returnSeal)) {
            $json['warn'] = "请选择需要归还的印章";
        } elseif (empty($field['returnDate'])) {
            $json['warn'] = '请选择归还日期';
        } else {
            $this->startTrans();
            $returnSeal = array_filter(array_unique(array_merge($returnSeal, explode(',', $info['returnSeal']))));
            asort($returnSeal);
            $field['returnSeal'] = implode(',', $returnSeal);
            $oldSeal = explode(',', $info['name']);
            $field['workFlow'] = '部分归还';
            if ($returnSeal == asort($oldSeal)) {
                $field['workFlow'] = '已归还';
            }
            $json['warn'] = update(array('table' => self::table, 'field' => $field, 'where' => " id = '$info[id]'"));
            $bool = static::insert(array('table' => 'seal_return_record', 'field' => ['sealRecordId' => $info['id'], 'stid' => self::$stid, 'returnDate' => $field['returnDate'], 'text' => $this->post('text'), 'sealSerial' => implode(',', $returnSeal)]));
            if ($bool != '新增成功') {
                $json['warn'] = $bool;
            }
            $bool = static::update(array('table'=>'seal','field'=>['isOccupy'=>0],'where'=>"id in ('".implode("','",$returnSeal)."')"));
            if ($bool != '更新成功') {
                $json['warn'] = $bool;
            }
            if (in_array($json['warn'], ['更新成功', '新增成功'])) {
                $this->commitTrans();
                $sealName = '';
                foreach ($returnSeal as $sealId) {
                    $seal = query('seal', "id = '$sealId'");
                    $sealName .= $seal['name'] . ',';
                }
                $text = $this->control['name'] . "归还用章记录【{$info['orderNo']}】， id：{$info['id']}成功，归还印章:{$sealName}<br>";
                //添加日志
                $this->logText(["type" => self::page, "text" => $text]);
                $_SESSION['warn'] = "归还成功";
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
                $json['warn'] = 2;
            } else {
                $this->rollback();
            }
        }
        //返回
        return json_encode($json, 320);
    }


    /**
     * 盖章
     */
    public function seal(): bool|string
    {
        $formName = 'listForm';
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must . "用章日期：" => text(array('name' => 'signTime', 'laydate' => [], 'value' => $this->date)),
            ),
            array(
                must . "用章份数：" => text(array('name' => 'num', 'value' => 1)),
            )
        )));
        //返回
        return $this->layer(array("title" => "盖章", "height" => 220, "html" => $html, 'formTwo' => $formName));
    }

    /**
     * 盖章
     */
    public function sealEdit(): bool|string
    {
        $idArr = $this->post('listId');
        $field = [
            'sealDate' => $this->post('signTime'),
            'sealNum' => $this->post('num'),
            'sealStid' => self::$stid,
            'workFlow' => '已用章'
        ];
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有" . self::title . "的编辑权限";
        } elseif (static::is_null_array($idArr)) {
            $json['warn'] = "请选择数据";
        } elseif (empty($field['sealDate'])) {
            $json['warn'] = '请选择用章日期';
        } elseif (empty($field['sealNum']) || preg_match(checkInteger, $field['sealNum']) == 0) {
            $json['warn'] = '请填写用章份数';
        } else {
            $x = 0;
            $text = '';
            foreach ($idArr as $id) {
                $info = query(self::table, "id = '$id'");
                if ($info['workFlow'] != '待用章') {
                    $text .= $this->control['name'] . "盖章【{$info['orderNo']}】， id：{$id} 失败：不是待用章状态<br>";
                } elseif ($info['isOut'] == '是') {
                    $text .= $this->control['name'] . "盖章【{$info['orderNo']}】， id：{$id} 失败：此记录为外带申请<br>";
                } else {
                    $warn = update(array('table' => self::table, 'field' => $field, 'where' => " id = '$id'"));
                    if ($warn == '更新成功') {
                        $x++;
                        //发送待办
                        $text .= $this->control['name'] . "盖章【{$info['orderNo']}】， id：{$id}成功，盖章日期:{$this->post('signTime')}<br>";
                    } else {
                        $text .= $this->control['name'] . "盖章【{$info['orderNo']}】， id：{$id} 失败，更新失败<br>";
                    }
                }
            }
            if ($text) {
                //添加日志
                $this->logText(["type" => self::page, "text" => $text]);
            }
            $_SESSION['warn'] = "成功盖章了{$x}条记录，详情请查看系统日志";
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
            $json['warn'] = 2;
        }
        //返回
        return json_encode($json, 320);
    }


    /**
     * 外借
     */
    public function out(): bool|string
    {
        $formName = 'listForm';
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must . "借出日期：" => text(array('name' => 'copyDate', 'laydate' => [], 'value' => $this->date)),
            ),
            array(
                "应还日期：" => text(array('name' => 'backDate', 'laydate' => [], 'value' => '')),
            ),
        )));
        //返回
        return $this->layer(array("title" => "外借", "height" => 220, "html" => $html, 'formTwo' => $formName));
    }

    /**
     * 外借
     */
    public function outEdit(): bool|string
    {
        $idArr = $this->post('listId');
        $field = array(
            'borrowDate' => $this->post('copyDate'),
            'exReturnDate' => $this->post('backDate'),
            'borrowStid' => self::$stid,
            'workFlow' => '待归还'
        );
        $annotation = [
            'borrowDate' => '借出日期',
        ];
        $rules = [
            'borrowDate' => 'required',
        ];
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有" . self::title . "的编辑权限";
        } elseif (static::is_null_array($idArr)) {
            $json['warn'] = "请选择数据";
        } elseif ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
        } else {
            $x = 0;
            $text = '';
            foreach ($idArr as $id) {
                $info = query(self::table, "id = '$id'");
                $idArr = explode(',', $info['name']);
                $warn = '';
                foreach ($idArr as $sealId) {
                    $seal = query('seal', "id = '$sealId'");
                    if ($seal['isOccupy']) {
                        $warn = "印章申请【{$info['orderNo']}】中印章【$seal[name]】已有其他人使用，暂不能外借<br>";
                    }
                }
                if ($info['workFlow'] != '待用章') {
                    $text .= $this->control['name'] . "外借印章【{$info['orderNo']}】， id：{$id} 失败：不是待用章状态<br>";
                } elseif ($info['isOut'] != '是') {
                    $text .= $this->control['name'] . "外借印章【{$info['orderNo']}】， id：{$id} 失败：此记录不可外带<br>";
                } elseif ($warn) {
                    $text .= $warn;
                } else {
                    $warn = update(array('table' => self::table, 'field' => $field, 'where' => " id = '$id'"));
                    if ($warn == '更新成功') {
                        static::update(array('table' => 'seal', 'field' => ['isOccupy' => 1], 'where' => "id in ('" . implode("','", $idArr) . "')"));
                        $x++;
                        //发送待办
                        $text .= $this->control['name'] . "外借印章【{$info['orderNo']}】， id：{$id}，借出日期:{$field['borrowDate']}<br>";
                    } else {
                        $text .= $this->control['name'] . "外借印章【{$info['orderNo']}】， id：{$id} 失败，更新失败<br>";
                    }
                }
            }
            if ($text) {
                //添加日志
                $this->logText(["type" => self::page, "text" => $text]);
            }
            $_SESSION['warn'] = "成功外借了{$x}个用章，详情请查看系统日志";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        //返回
        return json_encode($json, 320);
    }


    /*客户管理-客户详情页*/
    public function detail()
    {
        $info = query(self::table, "id = '" . $this->get('id') . "'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );
            //按钮
            $button = [];
            if ($this->power(self::page, "edit") && $info['workFlow'] == '待用章') {
                //按钮
                $button[] = [
                    "name" => "借出",
                    "type" => "顶部页卡",
                    "title" => "借出",
                    "url" => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=edit&id=' . $info['id'],
                ];

            }
            $audit = query('audit', " targetId = '$info[id]'");
            $obj = new performanceScoreClass();
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                "基本信息" => array(
                    array(
                        "印章名称" => sealRecordClass::showSealName($info['name']),
                        "是否外带" => $info['isOut'],
                        "同行人" => $obj->findMember($info['member'], 2),
                    ),
                    array(
                        "外带天数" => $info['outDay'],
                        "用章文件份数" => $info['fileNum'],
                    ),
                    array(
                        "用途说明" => $info['text'],
                    ),
                ),
                "附件" => array(
                    array(
                        fileUploadClass::showFile($info['id'], '用章记录')
                    ),
                ),
                '用章记录' => array(
                    array(
                        "用章日期" => $info['sealDate'],
                        "文件份数" => $info['sealNum'],
                        "经手人" => self::findStaff($info['sealStid']),
                    ),
                    array(
                        "借出日期" => $info['borrowDate'],
                        "应还日期" => $info['exReturnDate'],
                        "实际归还日期" => $info['returnDate'],
                    ),
                    array(
                        "借出经手人" => self::findStaff($info['borrowStid']),
                        "归还经手人" => self::findStaff($info['returnStid']),
                    ),
                ),
                '系统信息' => array(
                    array(
                        "单据编号" => $info['orderNo'],
                        "申请部门" => $info['deptName'],
                        "申请人" => self::findStaff($info['stid']),
                    ),
                    array(
                        "创建时间" => $info['time'],
                        "提交时间" => self::null($audit['commitTime']),
                        '状态' => $info['workFlow']
                    ),
                ),
            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'单据编号',
                    'aliasName'=>'单据编号',
                ],
                [
                    'columnName'=>'申请人',
                    'aliasName'=>'申请人',
                ],
                [
                    'columnName'=>'申请人部门',
                    'aliasName'=>'申请人部门',
                ],
                [
                    'columnName'=>'印章名称',
                    'aliasName'=>'印章名称',
                ],
                [
                    'columnName'=>'用途说明',
                    'aliasName'=>'用途说明',
                ],
                [
                    'columnName'=>'是否外带',
                    'aliasName'=>'是否外带',
                ],
                [
                    'columnName'=>'同行人',
                    'aliasName'=>'同行人',
                ],
                [
                    'columnName'=>'外带天数',
                    'aliasName'=>'外带天数',
                ],
                [
                    'columnName'=>'份数',
                    'aliasName'=>'份数',
                ],
                [
                    'columnName'=>'申请日期',
                    'aliasName'=>'申请日期',
                ],
                [
                    'columnName'=>'用章日期',
                    'aliasName'=>'用章日期',
                ],
                [
                    'columnName'=>'用章份数',
                    'aliasName'=>'用章份数',
                ],
                [
                    'columnName'=>'借出日期',
                    'aliasName'=>'借出日期',
                ],
                [
                    'columnName'=>'应还日期',
                    'aliasName'=>'应还日期',
                ],
                [
                    'columnName'=>'实际归还日期',
                    'aliasName'=>'实际归还日期',
                ],
                [
                    'columnName'=>'状态',
                    'aliasName'=>'状态',
                ],
            ]
        };
    }
}
